/*
 * @Description:
 * @Author: william
 * @Date: 2024-03-29 10:11:42
 * @LastEditors: william
 * @LastEditTime: 2025-06-05 11:17:52
 */

export const useTableColumnWidth = _this => {
  const { refTable } = _this
  const columnWidthObj = ref()

  const getTableColumnWidth = cb => {
    nextTick(() => {
      columnWidthObj.value = {}
      // 获取行rows
      const tableEle = refTable?.refBaseTable?.$el
      if (!tableEle) return
      const rows = tableEle.querySelectorAll(
        '.el-table__body-wrapper .el-table__row'
      )
      if (!rows.length) return
      // 获取props
      const hideRows = tableEle.querySelectorAll(
        '.hidden-columns>div:not(.ignore)'
      )
      // 每一行的列总数
      const cells = rows[0].cells
      Array.from(cells).forEach((cell, i) => {
        // 获取prop属性
        const prop = hideRows[i].getAttribute('data-prop')
        if (!prop) return
        // 计算一列内容最宽的宽度
        const maxVal = Array.from(rows).reduce((maxWidth, row) => {
          const cellsEle = row.cells[i]
          const cellEle = cellsEle.querySelector('.cell')
          // 临时修改样式以计算实际宽度
          cellsEle.style.display = 'inline-block'
          cellsEle.style.width = '100vw'
          // 比较一列最长的宽度数值
          cellEle.style.display = 'inline-block'
          const width = cellEle.getBoundingClientRect().width + 1 // 必须用这个方法，否则小数点会被忽略
          // 将表格列的元素恢复为表格布局
          cellsEle.style.display = 'table-cell'
          cellsEle.style.width = 'auto'
          cellEle.style.display = 'block'

          return Math.max(maxWidth, width)
        }, 0)
        // 防止相同的prop被覆盖，只取最大值
        columnWidthObj.value[prop] = Math.ceil(
          Math.max(maxVal, columnWidthObj.value[prop] || 0)
        )
      })
      cb(columnWidthObj.value)
      // console.log('this.columnWidthObj', columnWidthObj.value)
    })
  }

  return {
    columnWidthObj,
    getTableColumnWidth
  }
}
